<template>
  <div class="sales-outbound-page">
    <el-card shadow="never" class="search-card">
      <div class="search-card__header">
        <div class="search-title">
          <el-icon class="search-title__icon"><Box /></el-icon>
          <div>
            <p class="search-subtitle">仓库管理 · 销售出库</p>
            <h2 class="search-heading">销售出库列表</h2>
          </div>
        </div>
        <div class="search-header__actions">
          <el-button :icon="RefreshLeft" @click="handleReset">重置</el-button>
          <el-button
            type="primary"
            :icon="Search"
            :loading="loading"
            @click="handleSearch"
          >
            查询
          </el-button>
        </div>
      </div>
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="出库单编号/名称">
          <el-input
            v-model="searchForm.outboundKeyword"
            placeholder="请输入出库单编号或名称"
            clearable
            class="search-input"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Document /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="产品名称/编号">
          <el-input
            v-model="searchForm.productKeyword"
            placeholder="请输入产品名称或编号"
            clearable
            class="search-input"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Cpu /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="出库日期">
          <el-date-picker
            v-model="searchForm.outboundDate"
            type="date"
            placeholder="请选择出库日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            clearable
            class="search-input"
            :prefix-icon="Calendar"
          />
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="never" class="table-card">
      <div class="table-header">
        <div class="table-header__info">
          <h3 class="table-title">
            <el-icon class="table-title__icon"><List /></el-icon>
            销售出库列表
          </h3>
          <p class="table-subtitle">
            共 <strong>{{ pagination.totalCount }}</strong> 条数据，当前第
            <strong>{{ pagination.pageIndex }}</strong> /
            <strong>{{ totalPages }}</strong> 页
          </p>
          <el-tag
            v-if="multipleSelection.length > 0"
            type="info"
            size="small"
            class="selection-tag"
          >
            已选择 {{ multipleSelection.length }} 项
          </el-tag>
        </div>
        <div class="table-header__actions">
          <el-button
            type="primary"
            :icon="Plus"
            class="action-btn add-btn"
            @click="handleAdd"
          >
            新增销售出库
          </el-button>
          <el-button
            :icon="Download"
            class="action-btn"
            :loading="exportLoading"
            @click="handleExport"
          >
            导出
          </el-button>
          <el-button
            type="danger"
            class="action-btn"
            :disabled="!multipleSelection.length"
            @click="handleBatchDelete"
          >
            批量删除
          </el-button>
        </div>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        class="sales-table"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column
          type="index"
          label="序号"
          width="70"
          :index="getIndex"
          align="center"
        />
        <el-table-column prop="outboundName" label="出库单名称" min-width="160">
          <template #default="{ row }">
            <span class="table-strong">{{ row.outboundName || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="outboundNo" label="出库单编号" min-width="140">
          <template #default="{ row }">
            <span class="code-chip">{{ row.outboundNo || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="inspectionOrderNo"
          label="出货检验单"
          min-width="140"
        />
        <el-table-column prop="outboundDate" label="出库日期" min-width="130">
          <template #default="{ row }">
            <span>{{ formatDate(row.outboundDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="salesOrderNo" label="销售单号" min-width="140" />
        <el-table-column prop="machineName" label="客户名称" min-width="140" />
        <el-table-column prop="productName" label="产品名称" min-width="140" />
        <el-table-column prop="productNo" label="产品编号" min-width="140" />
        <el-table-column
          prop="specification"
          label="规格型号"
          min-width="120"
        />
        <el-table-column
          prop="outboundQuantity"
          label="出库数量"
          min-width="110"
          align="right"
        />
        <el-table-column prop="unit" label="单位" width="90" align="center" />
        <el-table-column
          prop="warehouseManager"
          label="仓库负责人"
          min-width="130"
        />
        <el-table-column label="状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag
              :type="getStatusMeta(row.stats).tagType"
              effect="light"
              class="status-tag"
            >
              {{ getStatusMeta(row.stats).label }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right" align="center">
          <template #default="{ row }">
            <div class="table-actions">
              <el-button
                type="primary"
                link
                size="small"
                @click="handleExecute(row)"
                :loading="isActionLoading(row.id, 'execute')"
                :disabled="row.stats !== 0"
              >
                出库
              </el-button>
              <el-button
                type="warning"
                link
                size="small"
                @click="handleEdit(row)"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                link
                size="small"
                @click="handleDelete(row)"
                :loading="isActionLoading(row.id, 'delete')"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
        <template #empty>
          <div class="empty-state">
            <el-icon class="empty-icon"><List /></el-icon>
            <p>暂无销售出库数据</p>
            <el-button type="primary" :icon="Plus" @click="handleAdd"
              >立即创建</el-button
            >
          </div>
        </template>
      </el-table>

      <div class="table-footer">
        <div class="pagination-wrapper">
          <el-button
            size="small"
            :icon="DArrowLeft"
            @click="gotoFirst"
            :disabled="pagination.pageIndex === 1"
            class="pagination-btn"
            >首页</el-button
          >
          <el-button
            size="small"
            :icon="ArrowLeft"
            @click="gotoPrev"
            :disabled="pagination.pageIndex === 1"
            class="pagination-btn"
            >上一页</el-button
          >
          <el-pagination
            v-model:current-page="pagination.pageIndex"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 30, 50]"
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.totalCount"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            class="pagination-component"
          />
          <el-button
            size="small"
            :icon="ArrowRight"
            @click="gotoNext"
            :disabled="pagination.pageIndex >= totalPages"
            class="pagination-btn"
            >下一页</el-button
          >
          <el-button
            size="small"
            :icon="DArrowRight"
            @click="gotoLast"
            :disabled="pagination.pageIndex >= totalPages"
            class="pagination-btn"
            >尾页</el-button
          >
        </div>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import {
  ArrowLeft,
  ArrowRight,
  Box,
  Calendar,
  Cpu,
  DArrowLeft,
  DArrowRight,
  Document,
  Download,
  List,
  Plus,
  RefreshLeft,
  Search,
} from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { computed, onMounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import https from "@/Http/http";
import moment from "moment";

type StatusTagType = "" | "success" | "warning" | "info" | "danger";

interface SalesOutboundItem {
  id: number;
  outboundNo: string;
  outboundName: string;
  inspectionOrderNo?: string;
  inspectionOrderName?: string;
  outboundDate?: string;
  salesOrderNo?: string;
  machineName?: string;
  customerId?: number | null;
  productName?: string;
  productNo?: string;
  specification?: string;
  unit?: string;
  productionDate?: string | null;
  expiryDate?: string | null;
  batchNoId?: number | null;
  batchNo?: string;
  batch?: string | null;
  outboundQuantity?: number;
  warehouseId?: string | null;
  warehouseName?: string;
  warehouseManager?: string;
  stats?: number;
  remark?: string;
  detailId?: number | null;
}

const STATUS_META: Record<number, { label: string; tagType: StatusTagType }> = {
  0: { label: "待出库", tagType: "warning" },
  1: { label: "已出库", tagType: "success" },
};

const getStatusMeta = (status?: number | null) => {
  const normalized = Number.isFinite(status) ? Number(status) : 0;
  return STATUS_META[normalized] ?? { label: "未知", tagType: "info" };
};

const router = useRouter();

const tableData = ref<SalesOutboundItem[]>([]);
const loading = ref(false);
const exportLoading = ref(false);
const multipleSelection = ref<SalesOutboundItem[]>([]);
const actionLoading = ref<{
  id: number | null;
  action: "execute" | "delete" | null;
}>({
  id: null,
  action: null,
});

const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
});

const searchForm = reactive({
  outboundKeyword: "",
  productKeyword: "",
  outboundDate: "" as string | null,
});

const totalPages = computed(() =>
  Math.max(1, Math.ceil(pagination.totalCount / pagination.pageSize))
);

const getIndex = (index: number) => {
  return (pagination.pageIndex - 1) * pagination.pageSize + index + 1;
};

const formatDate = (value: string | Date | null | undefined) => {
  if (!value) return "-";
  return moment(value).format("YYYY-MM-DD");
};

const formatDateInput = (value: string | Date | null | undefined) => {
  if (!value) return "";
  return moment(value).format("YYYY-MM-DD");
};

const buildDetailPayload = (row: SalesOutboundItem) => ({
  id: row.detailId ?? undefined,
  productName: row.productName || "",
  productNo: row.productNo || "",
  specification: row.specification || "",
  unit: row.unit || "",
  productionDate: formatDateInput(row.productionDate ?? null) || undefined,
  expiryDate: formatDateInput(row.expiryDate ?? null) || undefined,
  batchNo: row.batchNo || "",
  batch: row.batch || row.batchNo || "",
  batchNoId: row.batchNoId ?? null,
  outboundQuantity: row.outboundQuantity ?? 0,
  warehouseId:
    row.warehouseId && row.warehouseId !== ""
      ? String(row.warehouseId)
      : undefined,
  warehouseName: row.warehouseName || "",
  warehouseManager: row.warehouseManager || "",
});

const buildEditPayload = (row: SalesOutboundItem) => ({
  id: row.id,
  outboundNo: row.outboundNo || "",
  outboundName: row.outboundName || "",
  inspectionOrderId: null,
  inspectionOrderNo: row.inspectionOrderNo || "",
  inspectionOrderName: row.inspectionOrderName || row.inspectionOrderNo || "",
  outboundDate: formatDateInput(row.outboundDate ?? null),
  salesOrderNo: row.salesOrderNo || "",
  machineName: row.machineName || "",
  customerId: row.customerId ?? null,
  customerName: row.machineName || "",
  remark: row.remark || "",
  totalQuantity: row.outboundQuantity ?? 0,
  systemGenerated: false,
  details: [buildDetailPayload(row)],
});

const buildQueryParams = () => {
  const params: Record<string, unknown> = {
    PageIndex: pagination.pageIndex,
    PageSize: pagination.pageSize,
  };
  if (searchForm.outboundKeyword) {
    params.OutboundKeyword = searchForm.outboundKeyword.trim();
  }
  if (searchForm.productKeyword) {
    params.ProductKeyword = searchForm.productKeyword.trim();
  }
  if (searchForm.outboundDate) {
    params.OutboundDate = searchForm.outboundDate;
  }
  return params;
};

const parseResponse = (res: any) => {
  const responseData = res?.data ?? {};
  const code = responseData.code ?? responseData.Code;

  // 检查错误码
  if (code === -1 || code === 0) {
    const msg = responseData.msg ?? responseData.Msg ?? "获取销售出库列表失败";
    throw new Error(msg);
  }

  // 解析数据列表
  let dataList: any[] = [];
  if (responseData.data !== undefined) {
    dataList = Array.isArray(responseData.data) ? responseData.data : [];
  } else if (responseData.Data !== undefined) {
    dataList = Array.isArray(responseData.Data) ? responseData.Data : [];
  } else if (Array.isArray(res?.data)) {
    dataList = res.data;
  }

  // 解析总数
  const total =
    responseData.totalCount ?? responseData.TotalCount ?? dataList.length;

  return { list: dataList, total };
};

const loadSalesOutboundList = () => {
  loading.value = true;
  https.Reads.get("/Warehouse/SalesOutboundList", {
    params: buildQueryParams(),
  })
    .then((res: any) => {
      const { list, total } = parseResponse(res);
      tableData.value = list.map((item: any) => {
        const rawWarehouseId =
          item.warehouseId ?? item.WarehouseId ?? item.warehouse_id ?? null;
        const normalizedWarehouseId =
          rawWarehouseId === null ||
          rawWarehouseId === undefined ||
          rawWarehouseId === ""
            ? null
            : String(rawWarehouseId);
        const normalizedBatch =
          item.batch ?? item.Batch ?? item.batchNo ?? item.BatchNo ?? "";

        return {
          id: item.id ?? item.Id,
          outboundNo: item.outboundNo ?? item.OutboundNo ?? "",
          outboundName: item.outboundName ?? item.OutboundName ?? "",
          inspectionOrderNo:
            item.inspectionOrderNo ?? item.InspectionOrderNo ?? "",
          inspectionOrderName:
            item.inspectionOrdeNmae ??
            item.InspectionOrdeNmae ??
            item.inspectionOrderName ??
            item.InspectionOrderName ??
            "",
          outboundDate: item.outboundDate ?? item.OutboundDate ?? "",
          salesOrderNo: item.salesOrderNo ?? item.SalesOrderNo ?? "",
          machineName: item.machineName ?? item.MachineName ?? "",
          customerId: item.customerId ?? item.CustomerId ?? null,
          productName: item.productName ?? item.ProductName ?? "",
          productNo: item.productNo ?? item.ProductNo ?? "",
          specification: item.specification ?? item.Specification ?? "",
          unit: item.unit ?? item.Unit ?? "",
          productionDate: item.productionDate ?? item.ProductionDate ?? null,
          expiryDate: item.expiryDate ?? item.ExpiryDate ?? null,
          batchNoId: item.batchNoId ?? item.BatchNoId ?? null,
          batchNo: normalizedBatch,
          batch: normalizedBatch,
          outboundQuantity: item.outboundQuantity ?? item.OutboundQuantity ?? 0,
          warehouseId: normalizedWarehouseId,
          warehouseName: item.warehouseName ?? item.WarehouseName ?? "",
          warehouseManager:
            item.warehouseManager ?? item.WarehouseManager ?? "",
          stats: Number(item.stats ?? item.Stats ?? 0),
          remark: item.remark ?? item.Remark ?? "",
          detailId: item.detailId ?? item.DetailId ?? null,
        };
      });
      pagination.totalCount = total;
    })
    .catch((error: any) => {
      console.error("获取销售出库列表失败：", error);
      const msg =
        error?.message ??
        error?.response?.data?.msg ??
        "获取销售出库列表失败，请稍后重试";
      ElMessage.error(msg);
      tableData.value = [];
      pagination.totalCount = 0;
    })
    .finally(() => {
      loading.value = false;
    });
};

onMounted(() => {
  loadSalesOutboundList();
});

const handleSearch = () => {
  pagination.pageIndex = 1;
  loadSalesOutboundList();
};

const handleReset = () => {
  searchForm.outboundKeyword = "";
  searchForm.productKeyword = "";
  searchForm.outboundDate = null;
  handleSearch();
};

const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  pagination.pageIndex = 1;
  loadSalesOutboundList();
};

const handleCurrentChange = (val: number) => {
  pagination.pageIndex = val;
  loadSalesOutboundList();
};

const gotoFirst = () => {
  if (pagination.pageIndex !== 1) {
    pagination.pageIndex = 1;
    loadSalesOutboundList();
  }
};

const gotoPrev = () => {
  if (pagination.pageIndex > 1) {
    pagination.pageIndex -= 1;
    loadSalesOutboundList();
  }
};

const gotoNext = () => {
  if (pagination.pageIndex < totalPages.value) {
    pagination.pageIndex += 1;
    loadSalesOutboundList();
  }
};

const gotoLast = () => {
  if (pagination.pageIndex !== totalPages.value) {
    pagination.pageIndex = totalPages.value;
    loadSalesOutboundList();
  }
};

const handleSelectionChange = (rows: SalesOutboundItem[]) => {
  multipleSelection.value = rows;
};

const handleAdd = () => {
  router.push({
    path: "/SalesOutboundAdd",
    query: { mode: "add" },
  });
};

const handleEdit = (row: SalesOutboundItem) => {
  if (!row || !row.id) {
    ElMessage.warning("未找到需要编辑的销售出库记录");
    return;
  }
  try {
    const payload = buildEditPayload(row);
    router.push({
      path: "/SalesOutboundAdd",
      query: {
        mode: "edit",
        editId: String(row.id),
        editData: encodeURIComponent(JSON.stringify(payload)),
      },
    });
  } catch (error) {
    console.error("跳转编辑页面失败:", error);
    ElMessage.error("跳转编辑页面失败，请稍后重试");
  }
};

const setActionLoading = (
  id: number | null,
  action: "execute" | "delete" | null
) => {
  actionLoading.value = { id, action };
};

const isActionLoading = (id: number, action: "execute" | "delete") => {
  return actionLoading.value.id === id && actionLoading.value.action === action;
};

const handleExecute = (row: SalesOutboundItem) => {
  if (row.stats !== 0) {
    ElMessage.warning("仅待出库状态可执行出库");
    return;
  }
  ElMessageBox.confirm(
    `确认执行出库单「${row.outboundName}」的出库操作吗？`,
    "确认出库",
    {
      type: "warning",
      confirmButtonText: "确认出库",
      cancelButtonText: "取消",
    }
  )
    .then(() => {
      setActionLoading(row.id, "execute");
      return https.Writes.put("/Warehouse/SalesOutboundExecute", {
        Id: row.id,
      });
    })
    .then((res: any) => {
      const responseData = res?.data ?? {};
      const code = responseData.code ?? responseData.Code;
      if (code === 1) {
        ElMessage.success(responseData.msg ?? responseData.Msg ?? "出库成功");
        loadSalesOutboundList();
      } else {
        const errorMsg = responseData.msg ?? responseData.Msg ?? "出库失败";
        throw new Error(errorMsg);
      }
    })
    .catch((error: any) => {
      if (error !== "cancel") {
        console.error("执行出库失败：", error);
        const errorMsg =
          error?.message ??
          error?.response?.data?.msg ??
          error?.response?.data?.Msg ??
          "出库失败，请稍后重试";
        ElMessage.error(errorMsg);
      } else {
        ElMessage.info("已取消出库操作");
      }
    })
    .finally(() => {
      setActionLoading(null, null);
    });
};

const handleDelete = (row: SalesOutboundItem) => {
  ElMessageBox.confirm(
    `确认删除出库单「${row.outboundName}」吗？`,
    "删除确认",
    {
      type: "warning",
      confirmButtonText: "确认删除",
      cancelButtonText: "取消",
      dangerouslyUseHTMLString: false,
    }
  )
    .then(() => {
      setActionLoading(row.id, "delete");
      return https.Writes.put("/Warehouse/SalesOutboundDelete", {
        Id: row.id,
      });
    })
    .then((res: any) => {
      const responseData = res?.data ?? {};
      const code = responseData.code ?? responseData.Code;
      if (code === 1) {
        ElMessage.success(responseData.msg ?? responseData.Msg ?? "删除成功");
        loadSalesOutboundList();
      } else {
        const errorMsg = responseData.msg ?? responseData.Msg ?? "删除失败";
        throw new Error(errorMsg);
      }
    })
    .catch((error: any) => {
      if (error !== "cancel") {
        console.error("删除销售出库失败：", error);
        const errorMsg =
          error?.message ??
          error?.response?.data?.msg ??
          error?.response?.data?.Msg ??
          "删除失败，请稍后重试";
        ElMessage.error(errorMsg);
      } else {
        ElMessage.info("已取消删除");
      }
    })
    .finally(() => {
      setActionLoading(null, null);
    });
};

const handleBatchDelete = () => {
  if (!multipleSelection.value.length) {
    ElMessage.warning("请选择需要删除的销售出库记录");
    return;
  }

  const ids = multipleSelection.value.map((item) => item.id);
  const names = multipleSelection.value
    .map((item) => item.outboundName)
    .join("、");

  ElMessageBox.confirm(
    `确认批量删除选中的 ${ids.length} 条销售出库记录吗？\n\n包含：${names}`,
    "批量删除确认",
    {
      type: "warning",
      confirmButtonText: "确认删除",
      cancelButtonText: "取消",
      dangerouslyUseHTMLString: false,
    }
  )
    .then(() => {
      loading.value = true;
      return https.Writes.delete("/Warehouse/SalesOutboundDeletes", {
        data: { Ids: ids },
      });
    })
    .then((res: any) => {
      const responseData = res?.data ?? {};
      const code = responseData.code ?? responseData.Code;
      if (code === 1) {
        ElMessage.success(
          responseData.msg ?? responseData.Msg ?? "批量删除成功"
        );
        // 清空选择
        multipleSelection.value = [];
        loadSalesOutboundList();
      } else {
        const errorMsg = responseData.msg ?? responseData.Msg ?? "批量删除失败";
        throw new Error(errorMsg);
      }
    })
    .catch((error: any) => {
      if (error !== "cancel") {
        console.error("批量删除销售出库失败：", error);
        const errorMsg =
          error?.message ??
          error?.response?.data?.msg ??
          error?.response?.data?.Msg ??
          "批量删除失败，请稍后重试";
        ElMessage.error(errorMsg);
      } else {
        ElMessage.info("已取消批量删除");
      }
    })
    .finally(() => {
      loading.value = false;
    });
};

const handleExport = async () => {
  if (exportLoading.value) {
    ElMessage.warning("导出任务正在进行中，请稍候...");
    return;
  }

  exportLoading.value = true;

  try {
    // 构建导出参数，不包含分页信息
    const exportParams: Record<string, unknown> = {};

    if (searchForm.outboundKeyword) {
      exportParams.OutboundKeyword = searchForm.outboundKeyword.trim();
    }
    if (searchForm.productKeyword) {
      exportParams.ProductKeyword = searchForm.productKeyword.trim();
    }
    if (searchForm.outboundDate) {
      exportParams.OutboundDate = searchForm.outboundDate;
    }

    const response = await https.Reads.get("/Warehouse/SalesOutboundExport", {
      params: exportParams,
      responseType: "blob",
      timeout: 60000, // 60秒超时
    });

    // 检查响应是否为blob
    if (!(response.data instanceof Blob)) {
      throw new Error("导出数据格式错误");
    }

    const blob = new Blob([response.data], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    });

    // 检查blob大小
    if (blob.size === 0) {
      throw new Error("导出文件为空，请检查数据");
    }

    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;

    // 生成文件名
    const timestamp = new Date()
      .toISOString()
      .replace(/[-:T]/g, "")
      .slice(0, 14);
    link.download = `销售出库明细_${timestamp}.xlsx`;

    // 添加到DOM并触发下载
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    // 清理URL对象
    URL.revokeObjectURL(url);

    ElMessage.success("销售出库数据导出成功，请查看下载文件");
  } catch (error: any) {
    console.error("导出销售出库数据失败：", error);

    let errorMsg = "导出失败，请稍后重试";

    if (error?.response?.status === 404) {
      errorMsg = "导出接口不存在，请联系管理员";
    } else if (error?.response?.status === 500) {
      errorMsg = "服务器内部错误，请稍后重试";
    } else if (error?.code === "ECONNABORTED") {
      errorMsg = "导出超时，请稍后重试";
    } else if (error?.message) {
      errorMsg = error.message;
    }

    ElMessage.error(errorMsg);
  } finally {
    exportLoading.value = false;
  }
};
</script>

<style scoped>
.sales-outbound-page {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding-bottom: 24px;
  background: #f5f7fa;
  min-height: 100vh;
}

.search-card,
.table-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 18px rgba(0, 0, 0, 0.08);
}

.search-card__header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  border-bottom: 1px solid #f0f2f5;
  padding-bottom: 16px;
}

.search-title {
  display: flex;
  align-items: center;
  gap: 16px;
}

.search-title__icon {
  font-size: 32px;
  color: #409eff;
}

.search-subtitle {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.search-heading {
  margin: 4px 0 0 0;
  font-size: 20px;
  font-weight: 700;
  color: #303133;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.search-input {
  width: 240px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f2f5;
}

.table-title {
  display: flex;
  align-items: center;
  gap: 10px;
  margin: 0;
  font-size: 18px;
}

.table-title__icon {
  font-size: 22px;
  color: #409eff;
}

.table-subtitle {
  margin: 4px 0 0 0;
  color: #909399;
  font-size: 14px;
}

.selection-tag {
  margin-left: 12px;
}

.table-header__actions {
  display: flex;
  gap: 12px;
}

.action-btn {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.add-btn {
  background: linear-gradient(135deg, #00c6ff 0%, #0072ff 100%);
  border: none;
  color: #fff;
  box-shadow: 0 2px 8px rgba(0, 114, 255, 0.3);
}

.add-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 114, 255, 0.4);
}

.sales-table :deep(.el-table__header th) {
  background-color: #f5f7fa;
  font-weight: 600;
}

.table-strong {
  font-weight: 600;
  color: #303133;
}

.code-chip {
  padding: 4px 8px;
  background: rgba(64, 158, 255, 0.12);
  border-radius: 6px;
  font-family: "Courier New", monospace;
  color: #409eff;
}

.status-tag {
  min-width: 70px;
  justify-content: center;
}

.table-actions {
  display: flex;
  justify-content: center;
  gap: 8px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  padding: 40px 0;
  color: #909399;
}

.empty-icon {
  font-size: 40px;
  color: #c0c4cc;
}

.table-footer {
  margin-top: 24px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

.pagination-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  flex-wrap: wrap;
}

.pagination-btn {
  border-radius: 6px;
  transition: all 0.2s ease;
  font-weight: 500;
  padding: 8px 16px;
}

.pagination-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.pagination-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.pagination-component {
  margin: 0 8px;
}

.pagination-component :deep(.el-pagination__total) {
  font-weight: 500;
  color: #606266;
  margin-right: 16px;
}

.pagination-component :deep(.el-pagination__sizes) {
  margin-right: 16px;
}

.pagination-component :deep(.el-pagination__sizes .el-select) {
  width: 110px;
}

.pagination-component :deep(.el-pagination__jump) {
  margin-left: 16px;
  color: #606266;
}

.pagination-component :deep(.el-pagination__editor) {
  width: 50px;
}

.pagination-component :deep(.el-pager li) {
  border-radius: 4px;
  transition: all 0.2s ease;
  margin: 0 2px;
}

.pagination-component :deep(.el-pager li:hover) {
  background-color: #f0f9ff;
  color: #409eff;
}

.pagination-component :deep(.el-pager li.is-active) {
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
  color: #fff;
  font-weight: 600;
}

.pagination-component :deep(.btn-prev),
.pagination-component :deep(.btn-next) {
  border-radius: 4px;
  transition: all 0.2s ease;
}

.pagination-component :deep(.btn-prev:hover),
.pagination-component :deep(.btn-next:hover) {
  background-color: #f0f9ff;
  color: #409eff;
}

@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
  }
  .search-input {
    width: 100%;
  }
  .table-header {
    flex-direction: column;
    align-items: flex-start;
  }
  .table-header__actions {
    width: 100%;
    flex-wrap: wrap;
  }
  .table-footer {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>
